/*******************************************************************************
 * Copyright (c) 2012 March and Conquest.
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 ******************************************************************************/
package mrusanov.towers.localization;

import java.util.Locale;
import java.util.ResourceBundle;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Localization {
	private static final Logger LOG = LoggerFactory.getLogger(Localization.class);

	private static final String MESSAGES_BUNDLE_NAME = "messages";

	private static LocaleView lang;
	private static ResourceBundle resourceBundle;

	public static final LocaleView[] LOCALES = { new LocaleView("en", "lang.en"), new LocaleView("ru", "lang.ru") };

	static {
		setLang(LOCALES[0]);
	}

	private Localization() {
		throw new UnsupportedOperationException("Forbidden to instantiate!");
	}

	public static String getString(String key) {
		LOG.trace("getString invoked for key [" + key + "]");
		return resourceBundle.getString(key);
	}

	public static void setLang(LocaleView newLang) {
		LOG.info("Setting LocaleView " + newLang.getLocale());
		lang = newLang;
		resourceBundle = ResourceBundle.getBundle(MESSAGES_BUNDLE_NAME, new Locale(lang.locale));
	}

	public static void setLang(String newLang) {
		LOG.info("Setting locale " + newLang);

		for (LocaleView view : LOCALES) {
			if (view.locale.equals(newLang)) {
				setLang(view);
				return;
			}
		}

		throw new IllegalArgumentException("Unknown language:" + newLang);
	}

	public static LocaleView getLang() {
		return lang;
	}

	public static class LocaleView {
		private final String locale;
		private final String localeMessageKey;

		public LocaleView(String locale, String localeMessageKey) {
			super();
			this.locale = locale;
			this.localeMessageKey = localeMessageKey;
		}

		public String getLocale() {
			return locale;
		}

		@Override
		public String toString() {
			return Localization.getString(localeMessageKey);
		}
	}

}
